<template>
    <div>
        <el-upload
            class="upload-demo"
            :action="actionUrl(options.url)"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="successHandler"
             multiple
            :limit="5"
            :data="data"
            :on-exceed="handleExceed"
            :file-list="options.fileList">
            <template #file="{ file }">
                <div class="custom-file-item" :key="data.id">
                    <i class="el-icon-document"></i>
                    <span class="file-name">{{ file.name }}</span>
                    <!-- 下载按钮 -->
                    <el-button
                    type="text"
                    icon="el-icon-download"
                    @click="handleDownload(file)"
                    v-if="file.id"
                    >
                   
                    </el-button>
                    <el-button
                    type="text"
                    icon="el-icon-close"
                    @click="deleteFile(file)"
                    v-if="file.id && isEdit"
                    >
                    </el-button>
                </div>
                </template>
            <el-button size="small" type="primary" v-if="isEdit">点击上传</el-button>
        </el-upload>
        <file-view-dialog :options="fileOptions"></file-view-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue ,Emit} from 'vue-property-decorator';
import store from '@/store';
import FileViewDialog from '@/components/FileViewDialog.vue';

@Component({
  components: { FileViewDialog }
})
export default class FileUploadComp extends Vue {
    @Prop() private options!:any;
    @Prop() private dataId!:any;
    @Prop() private isEdit!:any;

    fileOptions:any = {
        dialogVisible:false,
        url:'',
        title:'',
        removeApi:null,
    }
    data:any ={
        id:''
    };
    headers: any = {
        'Authorization': 'Bearer ' + store.getters.token
    };

    get actionUrl() {
        return function (url) {
            return process.env.VUE_APP_BASE_API + url;
        }
    }

    handleDownload(file) {
  
        const link = document.createElement('a');
        link.href = process.env.VUE_APP_BASE_API +'/resources/file/' + file.id;
        link.setAttribute('download',file.name);
        link.click();
    }

    handleOpen(file){
        this.fileOptions.url = process.env.VUE_APP_BASE_API  +'/resources/file/' + file.id;
        this.fileOptions.type = 'application/pdf';// +  file.name.split('.')[1];
        this.fileOptions.title = file.name;
        this.fileOptions.dialogVisible = true;
    }

    deleteFile(file){
        if(!this.options.removeApi){
            this.$message.error(`文件${file.name}删除失败,没有配置删除API`);
            return;
        }
        this.beforeRemove(file,null).then(() =>{
         return this.options.removeApi({id:this.dataId,evidenceId:file.id});
        }).then(res=>{
            if(res.data){
                this.$message.success(`文件${file.name}删除成功`);
                this.options.fileList = this.options.fileList.filter(item => item.id !== file.id);
                return;
            }
            this.$message.error(`文件${file.name}删除失败`);
        });
    }

    @Emit('successHandler')
    successHandler(res, file, fileList){
         // 提取新上传文件的 ID
        const oldIds = this.options.fileList.map(item => item.id);
        res.data.forEach(item =>{
            if(!oldIds.includes(item.id)){
                this.options.fileList.push(item);
            }
        })
   
        // 过滤掉旧列表中可能存在的重复项（根据业务需求调整）
        this.$message.success(`文件${file.name}上传成功`);
    }   

    
    handleRemove(file, fileList) {
        console.log(file, fileList);
    }
    handlePreview(file) {
       console.log(file);
    }

    handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择5个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
    beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
    }
    mounted(){
        this.data.id = this.dataId;
    }
  }
</script>
<style  scoped>

.custom-file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  border: 1px solid #ddd;
  margin-bottom: 4px;
}

.file-name {
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>